import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/comic_user_model.dart';
import '../utils/user_manager.dart';
import '../utils/http_helper.dart';
import '../utils/aes_encryption.dart';
import '../models/comic_login_model.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

// 认证状态数据模型
class AuthState {
  final bool isLoggedIn;
  final String userEmail;
  final String userId;
  final bool isLoading;
  final String? errorMessage;
  final UserData? userInfo;

  const AuthState({
    this.isLoggedIn = false,
    this.userEmail = '',
    this.userId = '',
    this.isLoading = false,
    this.errorMessage,
    this.userInfo,
  });

  AuthState copyWith({
    bool? isLoggedIn,
    String? userEmail,
    String? userId,
    bool? isLoading,
    String? errorMessage,
    UserData? userInfo,
  }) {
    return AuthState(
      isLoggedIn: isLoggedIn ?? this.isLoggedIn,
      userEmail: userEmail ?? this.userEmail,
      userId: userId ?? this.userId,
      isLoading: isLoading ?? this.isLoading,
      errorMessage: errorMessage,
      userInfo: userInfo ?? this.userInfo,
    );
  }
}

// 认证状态管理器
class AuthNotifier extends StateNotifier<AuthState> {
  AuthNotifier() : super(const AuthState()) {
    _initializeAuth();
  }

  // 初始化认证状态（从本地存储恢复）
  Future<void> _initializeAuth() async {
    try {
      // 首先检查是否已登录
      final isLoggedIn = await UserManager.isLoggedIn();
      if (isLoggedIn) {
        // 获取本地保存的登录信息
        final loginInfo = await UserManager.getLoginInfo();
        if (loginInfo != null && loginInfo.token != null) {
          // 尝试获取用户信息
          final userInfo = await UserManager.getUserInfo();
          if (userInfo != null) {
            state = state.copyWith(
              isLoggedIn: true,
              userEmail: userInfo.email ?? '',
              userInfo: userInfo,
            );
          } else {
            // 如果获取用户信息失败，但token存在，仍然标记为已登录
            state = state.copyWith(
              isLoggedIn: true,
              userEmail: '', // 临时使用token作为标识
            );
          }
        }
      }
    } catch (e) {
      print('Initialize auth error: $e');
      // 如果初始化失败，确保状态为未登录
      state = const AuthState();
    }
  }

  // 登录方法
  Future<bool> login(String email, String password) async {
    state = state.copyWith(isLoading: true, errorMessage: null);

    try {
      // 表单验证
      if (email.isEmpty || password.isEmpty) {
        _setError('Please fill in all fields');
        return false;
      }

      if (!_isValidEmail(email)) {
        _setError('Please enter a valid email address');
        return false;
      }

      if (password.length < 6) {
        _setError('Password must be at least 6 characters');
        return false;
      }

      // 发送登录请求
      final userResponse = await HttpUtil().postModel(
        'ComicMember/Login',
        data: {
          'accountName': email,
          'passWord': password,
          'loginType': AESUtil.encryptECB('0'),
          'platformId': 1,
        },
        fromJson: LoginTokenModel.fromJson,
      );

      if (userResponse?.status == 200 && userResponse?.result != null) {
        // 保存登录信息到本地
        await UserManager.saveLoginInfo(userResponse!.result!);

        // 获取用户详细信息
        final userInfo = await UserManager.getUserInfo();

        // 更新状态
        state = state.copyWith(
          isLoggedIn: true,
          userEmail: email,
          userInfo: userInfo,
          isLoading: false,
          errorMessage: null,
        );

        EasyLoading.showSuccess('Login successful!');
        return true;
      } else {
        final errorMessage = userResponse?.message ?? 'Login failed, please try again';
        _setError(errorMessage);
        return false;
      }
    } catch (e) {
      String errorMessage = 'Network connection failed, please check your network and try again';
      if (e.toString().contains('timeout')) {
        errorMessage = 'Request timeout, please try again';
      } else if (e.toString().contains('socket')) {
        errorMessage = 'Network connection error, please check your network settings';
      }
      _setError(errorMessage);
      print('Login error: $e');
      return false;
    }
  }

  // 退出登录
  Future<void> logout() async {
    try {
      await UserManager.clearLoginInfo();
      state = const AuthState();
      EasyLoading.showSuccess('Logged out successfully');
    } catch (e) {
      print('Logout error: $e');
    }
  }

  // 刷新用户信息
  Future<void> refreshUserInfo() async {
    try {
      final userInfo = await UserManager.getUserInfo();
      if (userInfo != null) {
        state = state.copyWith(userInfo: userInfo);
      }
    } catch (e) {
      print('Refresh user info error: $e');
    }
  }

  // 设置错误信息
  void _setError(String message) {
    state = state.copyWith(
      isLoading: false,
      errorMessage: message,
    );
    EasyLoading.showError(message);
  }

  // 清除错误信息
  void clearError() {
    state = state.copyWith(errorMessage: null);
  }

  // 邮箱格式验证
  bool _isValidEmail(String email) {
    return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  }
}

// Provider定义
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
  return AuthNotifier();
});

// 便捷的Provider（向后兼容）
final isLoggedInProvider = Provider<bool>((ref) {
  return ref.watch(authProvider).isLoggedIn;
});

final userEmailProvider = Provider<String>((ref) {
  return ref.watch(authProvider).userEmail;
});

final userInfoProvider = Provider<UserData?>((ref) {
  return ref.watch(authProvider).userInfo;
});

final authLoadingProvider = Provider<bool>((ref) {
  return ref.watch(authProvider).isLoading;
});
